package com.blog4j.user.utils;

import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blog4j.common.constants.CommonConstant;
import com.blog4j.common.enums.ErrorEnum;
import com.blog4j.common.enums.RoleEnum;
import com.blog4j.common.enums.UserVerifyContentTypeEnum;
import com.blog4j.common.enums.VerifyStatusEnum;
import com.blog4j.common.enums.YesOrNoEnum;
import com.blog4j.common.exception.Blog4jException;
import com.blog4j.common.utils.CommonUtil;
import com.blog4j.contentVerify.context.ContentVerifyContext;
import com.blog4j.contentVerify.context.VerifyResult;
import com.blog4j.contentVerify.enums.TextServiceEnum;
import com.blog4j.contentVerify.enums.VerifyResultEnum;
import com.blog4j.contentVerify.enums.VerifyTypeEnum;
import com.blog4j.contentVerify.model.TextVerifyModel;
import com.blog4j.contentVerify.processor.VerifyProcessor;
import com.blog4j.user.entity.RoleEntity;
import com.blog4j.user.entity.UserEntity;
import com.blog4j.user.entity.UserVerifyRecordEntity;
import com.blog4j.user.mapper.RoleMapper;
import com.blog4j.user.mapper.UserMapper;
import com.blog4j.user.mapper.UserVerifyRecordMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author 98k灬
 * @version v1.0.0
 * @Description : 功能描述
 * @Create on : 2024/7/30 12:17
 **/
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class UserUtil {
    private final UserMapper userMapper;
    private final RoleMapper roleMapper;
    private final VerifyProcessor verifyProcessor;
    private final UserVerifyRecordMapper userVerifyRecordMapper;

    /**
     * 获取当前的用户记录数
     *
     * @return 当前的用户记录数
     */
    public int getUserSize() {
        return userMapper.getId();
    }

    /**
     * 获取超级管理员的ID
     *
     * @return 超级管理员的ID
     */
    public String getSuperAdminUserId() {
        LambdaQueryWrapper<RoleEntity> wrapper = new LambdaQueryWrapper<RoleEntity>()
                .eq(RoleEntity::getRoleCode, RoleEnum.SUPER_ADMIN.getDesc());
        RoleEntity role = roleMapper.selectOne(wrapper);
        if (Objects.isNull(role)) {
            throw new Blog4jException(ErrorEnum.SYSTEM_ERROR);
        }

        LambdaQueryWrapper<UserEntity> wrapper1 = new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getRoleId, role.getRoleId());
        UserEntity user = userMapper.selectOne(wrapper1);
        return user.getUserId();
    }

    /**
     * 获取超级管理员的名称
     *
     * @return 超级管理员的名称
     */
    public String getSuperAdminUserName() {
        LambdaQueryWrapper<RoleEntity> wrapper = new LambdaQueryWrapper<RoleEntity>()
                .eq(RoleEntity::getRoleCode, RoleEnum.SUPER_ADMIN.getDesc());
        RoleEntity role = roleMapper.selectOne(wrapper);
        if (Objects.isNull(role)) {
            throw new Blog4jException(ErrorEnum.SYSTEM_ERROR);
        }

        LambdaQueryWrapper<UserEntity> wrapper1 = new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getRoleId, role.getRoleId());
        UserEntity user = userMapper.selectOne(wrapper1);
        return user.getUserName();
    }

    /**
     * 用户签名检测
     *
     * @param userSign 待检测的用户签名
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public boolean checkUserSign(String userSign, String userId) {
        boolean checkResult = Boolean.TRUE;
        if (StringUtils.isBlank(userSign) || StringUtils.isBlank(userId)) {
            return true;
        }
        VerifyResult verifyResult = this.getVerifyResult(userSign, TextServiceEnum.COMMENT_DETECTION.getService());
        // 获取阿里云内容审核接口失败 重试三次
        if (!verifyResult.getStatus()) {
            try {
                int retryTime = 0;
                while(retryTime < CommonConstant.DEFAULT_RETRY_TIMES) {
                    verifyResult = this.getVerifyResult(userSign, TextServiceEnum.COMMENT_DETECTION.getService());
                    if (verifyResult.getStatus()) {
                        break;
                    }
                    ThreadUtil.sleep(CommonConstant.DEFAULT_RETRY_INTERVAL_TIME);
                    retryTime += 1;
                }

                if (!verifyResult.getStatus()) {
                    // 重试了三次还是调用失败
                    UserVerifyRecordEntity userVerifyRecord = new UserVerifyRecordEntity();
                    userVerifyRecord.setVerifyContent(userSign)
                            .setContentType(UserVerifyContentTypeEnum.USER_NAME.getType())
                            .setUserId(userId)
                            .setNeedManualVerify(YesOrNoEnum.YES.getCode())
                            .setVerifyStatus(VerifyStatusEnum.WAIT.getStatus());
                    userVerifyRecordMapper.insert(userVerifyRecord);
                    return true;
                }
            } catch (Exception exception) {
                log.error("checkUserSign error .");
                throw new Blog4jException(ErrorEnum.SYSTEM_ERROR);
            }
        }

        VerifyResultEnum result = verifyResult.getResult();
        if (result == VerifyResultEnum.PASS) {
            return Boolean.TRUE;
        }
        UserVerifyRecordEntity userVerifyRecord = new UserVerifyRecordEntity();
        userVerifyRecord.setVerifyContent(userSign)
                .setContentType(UserVerifyContentTypeEnum.SIGN.getType())
                .setUserId(userId)
                .setVerifyResult(VerifyResultEnum.PASS.getDesc())
                .setVerifyStatus(VerifyStatusEnum.VERIFIED.getStatus())
                .setVerifyType(com.blog4j.common.enums.VerifyTypeEnum.MACHINE.getType())
                .setNeedManualVerify(YesOrNoEnum.NO.getCode())
                .setVerifyTime(CommonUtil.getCurrentDateTime());
        if (result == VerifyResultEnum.IN_DOUBT) {
            // 审核存疑
            userVerifyRecord.setVerifyStatus(VerifyStatusEnum.WAIT.getStatus())
                    .setVerifyResult(VerifyResultEnum.IN_DOUBT.getDesc())
                    .setNeedManualVerify(YesOrNoEnum.YES.getCode());
        } else if (result == VerifyResultEnum.REJECT) {
            // 审核拒绝
            userVerifyRecord.setVerifyResult(VerifyResultEnum.REJECT.getDesc())
                    .setRiskLevel(verifyResult.getRiskLevel())
                    .setRiskTips(verifyResult.getRiskTips())
                    .setRiskWords(verifyResult.getRiskWords())
                    .setRiskLabel(verifyResult.getLabels());
            checkResult = Boolean.FALSE;
        }
        userVerifyRecordMapper.insert(userVerifyRecord);
        return checkResult;
    }

    /**
     * 用户名风险检测
     *
     * @param userName 待检测的用户名称
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public boolean checkUserName(String userName, String userId) {
        boolean checkResult = Boolean.TRUE;
        if (StringUtils.isBlank(userName) || StringUtils.isBlank(userId)) {
            return true;
        }
        VerifyResult verifyResult = this.getVerifyResult(userName, TextServiceEnum.NICKNAME_DETECTION.getService());
        // 获取阿里云内容审核接口失败 重试三次
        if (!verifyResult.getStatus()) {
            try {
                int retryTime = 0;
                while(retryTime < CommonConstant.DEFAULT_RETRY_TIMES) {
                    verifyResult = this.getVerifyResult(userName, TextServiceEnum.NICKNAME_DETECTION.getService());
                    if (verifyResult.getStatus()) {
                        break;
                    }
                    ThreadUtil.sleep(CommonConstant.DEFAULT_RETRY_INTERVAL_TIME);
                    retryTime += 1;
                }

                if (!verifyResult.getStatus()) {
                    // 重试了三次还是调用失败
                    UserVerifyRecordEntity userNameVerifyRecord = new UserVerifyRecordEntity();
                    userNameVerifyRecord.setVerifyContent(userName)
                            .setContentType(UserVerifyContentTypeEnum.USER_NAME.getType())
                            .setUserId(userId)
                            .setNeedManualVerify(YesOrNoEnum.YES.getCode())
                            .setVerifyStatus(VerifyStatusEnum.WAIT.getStatus());
                    userVerifyRecordMapper.insert(userNameVerifyRecord);
                    return true;
                }
            } catch (Exception exception) {
                log.error("checkUserName error .");
                throw new Blog4jException(ErrorEnum.SYSTEM_ERROR);
            }
        }

        VerifyResultEnum result = verifyResult.getResult();
        if (result == VerifyResultEnum.PASS) {
            return Boolean.TRUE;
        }
        UserVerifyRecordEntity userVerifyRecord = new UserVerifyRecordEntity();
        userVerifyRecord.setVerifyContent(userName)
                .setContentType(UserVerifyContentTypeEnum.USER_NAME.getType())
                .setUserId(userId)
                .setVerifyStatus(VerifyStatusEnum.VERIFIED.getStatus())
                .setVerifyType(com.blog4j.common.enums.VerifyTypeEnum.MACHINE.getType())
                .setNeedManualVerify(YesOrNoEnum.NO.getCode())
                .setVerifyResult(VerifyResultEnum.PASS.getDesc())
                .setVerifyTime(CommonUtil.getCurrentDateTime());
        if (result == VerifyResultEnum.IN_DOUBT) {
            // 审核存疑
            userVerifyRecord.setVerifyStatus(VerifyStatusEnum.WAIT.getStatus())
                    .setVerifyResult(VerifyResultEnum.IN_DOUBT.getDesc())
                    .setNeedManualVerify(YesOrNoEnum.YES.getCode());
        } else if (result == VerifyResultEnum.REJECT) {
            // 审核拒绝
            userVerifyRecord.setVerifyResult(VerifyResultEnum.REJECT.getDesc())
                    .setRiskLevel(verifyResult.getRiskLevel())
                    .setRiskTips(verifyResult.getRiskTips())
                    .setRiskWords(verifyResult.getRiskWords())
                    .setRiskLabel(verifyResult.getLabels());
            checkResult = Boolean.FALSE;
        }
        userVerifyRecordMapper.insert(userVerifyRecord);
        return checkResult;
    }

    private VerifyResult getVerifyResult(String userName, String textService) {
        TextVerifyModel textVerifyModel = new TextVerifyModel();
        textVerifyModel.setTextContent(userName);
        textVerifyModel.setTextService(textService);
        ContentVerifyContext verifyContext = ContentVerifyContext.builder()
                .verifyType(VerifyTypeEnum.TEXT)
                .textVerifyModel(textVerifyModel)
                .build();
        verifyProcessor.contentVerify(verifyContext);
        return verifyContext.getVerifyResult();
    }
}
